using MySql.Data.MySqlClient;
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using SmartLink.Domain.Attribute;
using SmartLink.Infrastructure;

namespace SmartLink.Repository.Base
{
    public class DapperHelper
    {
        /// <summary>
        /// 获取entity type所对应的数据库表名称
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string GetTableName(Type type)
        {
            //var tableattr = type.GetCustomAttributes(false).Where(attr => attr.GetType().Name == "TableNameAttribute").SingleOrDefault() as dynamic;
            //if (tableattr != null)
            //    return tableattr.Name;
            //return type.Name;
            var cName = type.GetCustomAttributeValue<TableNameAttribute>(x => x.Name);
            return cName;
        }

        /// <summary>
        /// 获取实体对象的主键字段
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string GetPrimaryKey(Type type)
        {
            string cName = string.Empty;
            System.Reflection.PropertyInfo[] PIs = type.GetProperties();
            foreach (System.Reflection.PropertyInfo pis in PIs)
            {
                if (Attribute.GetCustomAttribute(pis, typeof(PrimaryKeyAttribute)) != null)
                {
                    cName = pis.Name;
                    break;
                }
            }
            return cName;
        }


        /// <summary>
        /// 获取默认的数据库Connection
        /// </summary>
        /// <returns></returns>
        public static MySqlConnection GetDefaultConnection()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["DapperConnection"].ConnectionString;
            //给批处理使用
            //string connectionString = ConfigurationManager.AppSettings["DapperConnection"];
            var connection = new MySqlConnection(connectionString);
            connection.Open();
            return connection;
        }

        /// <summary>
        /// 获取运行使用用户变量（@tamp）的数据库Connection
        /// </summary>
        /// <returns></returns>
        public static MySqlConnection GetAllowUserVariableConnection()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["DapperConnection"].ConnectionString;
            //给批处理使用
            //string connectionString = ConfigurationManager.AppSettings["DapperConnection"];
            var connection = new MySqlConnection("Allow User Variables=True;" + connectionString);
            connection.Open();
            return connection;
        }
    }
}
